package cn.paul.config;

import cn.paul.utils.PropertyUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * Created by paul on 2017-06-14.
 */
@ComponentScan(basePackages = "cn.paul.*", excludeFilters = {@ComponentScan.Filter
        (type = FilterType.ANNOTATION, classes = EnableWebMvc.class)})
@Configuration
@MapperScan(value = {"cn.paul.mapper"})
public class RootConfig {
    @Bean
    public DataSource dataSource() {

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setUrl("jdbc:mysql:///OLSHOP?useSSL=false");

//        dataSource.configFromPropety(PropertyUtil.loadProps("druid-config.properties"));
        return dataSource;


    }

    //分页插件
    @Bean
    public PageInterceptor pageInterceptor() throws IOException {
        PageInterceptor pageInterceptor = new PageInterceptor();
        pageInterceptor.setProperties(PropertyUtil.loadProps("pageInterceptor.properties"));
        return pageInterceptor;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();

        sqlSessionFactory.setDataSource(dataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactory.setMapperLocations
                (new Resource[]{resolver.getResource("classpath:mapper/UserMapper.xml")
                        , resolver.getResource("classpath:mapper/ItemMapper.xml")
                        , resolver.getResource("classpath:mapper/OrderMapper.xml")});
        sqlSessionFactory.setPlugins(new Interceptor[]{pageInterceptor()});

        return sqlSessionFactory;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}
